import React, { useImperativeHandle, forwardRef, useEffect } from 'react';
import { Form, Row, Col } from 'antd';
import FormControls from '@/components/FormControls';
import BaseEditor from '@/components/BaseEditor';
import "./index.less";

const getFormItemLabelCol = (item, max, initialLabelWidth) => {
  let labelWidth = item.labelWidth || initialLabelWidth || max.length * 18
  if (typeof labelWidth === 'number') {
    labelWidth += 'px'
  }
  return {
    style: {
      width: labelWidth,
    }
  }
}

const BaseForm = (props, ref) => {
  const { columns, initialValues = {}, labelWidth, ...other } = props;

  const maxLabel = columns.map(v => v.title).sort((a, b) => a?.length - b?.length)[columns.length - 1]

  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [initialValues, form])

  const submit = () => {
    form
      .validateFields()
      .then((values) => {
        if (props.onSubmit) {
          props.onSubmit(values);
        }
      })
      .catch(() => {});
  };

  const reset = () => {
    form.resetFields();
  };

  useImperativeHandle(ref, () => ({
    validateFields: () => {
      return form.validateFields();
    },
    submit: () => {
      submit();
    },
    reset: () => {
      reset();
    },
  }));

  const handleEditorChange = (html, fieldKey) => {
    form.setFieldValue(fieldKey, html);
  }

  return (
    <div className="form-layout">
      <Form
        onFinish={() => {
          submit();
        }}
        initialValues={initialValues}
        {...other}
        form={form}
      >
        <Row gutter={10} type="flex" align="middle">
          {columns.filter(item => !item.hidden).map((item) => {
            // colProps:每个Col的样式,formItemProps:每个表单项的属性
            const { colProps = {}, formItemProps = {}, fieldProps } = item;
            return (
              <Col
                xxl={item.itemSpan || (item.valueType === 'editor' ? 24 : 6)}
                xl={8}
                md={12} 
                xs={24}
                key={item.dataIndex}
                {...colProps}
              >
                <Form.Item
                  style={{ width: '100%' }}
                  label={item.title}
                  labelCol={getFormItemLabelCol(item, maxLabel, labelWidth)}
                  initialValue={item.initialValue}
                  name={item.dataIndex}
                  {...formItemProps}
                >
                  {
                    !item.renderFormItem ? (
                      item.valueType === 'editor' ? (
                        <BaseEditor value={initialValues[item.dataIndex]} onChange={(html) => handleEditorChange(html, item.dataIndex)} />
                        // <></>
                      ) : (
                        FormControls.getControlComponent(
                          item.valueType,
                          {
                            ...item,
                          }
                        )
                      )
                    ) : (
                      typeof item.renderFormItem === 'function' ? item.renderFormItem(item, { formItemProps, fieldProps }, form) : null
                    )
                  }
                </Form.Item>
              </Col>
            );
          })}
        </Row>
        {
          //children需要处理form指针问题
          props.children
        }
      </Form>
    </div>
  );
};

export default forwardRef(BaseForm);
